import { createStore } from 'vuex'
import CryptoJS from 'crypto-js'
import authApi from '@/api/common/LogAndRes'

export default createStore({
    state: {
        userInfo: null, // 保留原始状态名
        token: null,    // 保留原始状态名
        baseUrl: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000/', // 保留原始状态名
        isAuthenticated: false // 新增认证状态
    },
    mutations: {
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo
            state.isAuthenticated = !!userInfo // 更新认证状态
        },
        SET_TOKEN(state, token) {
            state.token = token
            state.isAuthenticated = !!token // 更新认证状态

            // 将token存储到localStorage
            if (token) {
                localStorage.setItem('authToken', token)
            } else {
                localStorage.removeItem('authToken')
            }
        },
        SET_BASE_URL(state, url) {
            state.baseUrl = url
        },
        // 新增登出状态清除
        LOGOUT(state) {
            state.userInfo = null
            state.token = null
            state.isAuthenticated = false
            localStorage.removeItem('authToken')
        }
    },
    actions: {
        // 保留原始action
        userInfo({ commit }, userInfo) {
            commit('SET_USER_INFO', userInfo)
        },

        // 新增登录action
        async login({ commit }, credentials) {
            try {
                // 密码加密
                const encryptedPassword = CryptoJS.SHA256(credentials.password).toString()

                const response = await authApi.login({
                    email: credentials.email,
                    password: encryptedPassword
                })

                if (response.data.success) {
                    commit('SET_USER_INFO', response.data.user)
                    commit('SET_TOKEN', response.data.token)
                    return true
                }
                return false
            } catch (error) {
                console.error('登录失败:', error)
                return false
            }
        },

        // 新增注册action
        async register({ commit, state }, userData) {
            try {
                // 密码加密
                userData.password = CryptoJS.SHA256(userData.password).toString()

                // 使用state.baseUrl作为API基地址
                const response = await authApi.register(userData, state.baseUrl) // 传递baseUrl

                if (response.data.success) {
                    commit('SET_USER_INFO', response.data.user)
                    commit('SET_TOKEN', response.data.token)
                    return true
                }
                return false
            } catch (error) {
                console.error('注册失败:', error)
                return false
            }
        },

        // 新增登出action
        logout({ commit }) {
            authApi.logout().finally(() => {
                commit('LOGOUT')
            })
        },

        // 新增检查认证状态action
        async checkAuth({ commit, state }) {
            const token = localStorage.getItem('authToken')
            if (token) {
                try {
                    // 使用state.baseUrl作为API基地址
                    const response = await authApi.getUserInfo(state.baseUrl) // 传递baseUrl
                    if (response.data.success) {
                        commit('SET_USER_INFO', response.data.user)
                        commit('SET_TOKEN', token)
                        return true
                    }
                } catch (error) {
                    console.error('验证失败:', error)
                }
            }
            commit('SET_TOKEN', null) // 清除无效token
            return false
        },

        // 新增更新API基地址action
        updateBaseUrl({ commit }, newUrl) {
            commit('SET_BASE_URL', newUrl)
        }
    },
    getters: {
        // 保留原始getter
        isAuthenticated: state => state.isAuthenticated,
        currentUser: state => state.userInfo,

        // 新增获取API基地址getter
        getApiBaseUrl: state => state.baseUrl
    }
})